package com.project.thread.demo;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class BlockingQueueTest {

    public static void main(String[] args) {
        final BlockingQueue queue = new ArrayBlockingQueue(10);
        AtomicInteger count = new AtomicInteger(1);
        //存数据
        for (int i = 0; i < 20; i++) {
            int finalI = i;
            new Thread(() -> {
//                while (true) {
                try {
                    synchronized (BlockingQueueTest.class) {
                        System.out.println(Thread.currentThread().getName() + "存放数据");
                        queue.put(finalI);
                        System.out.println(Thread.currentThread().getName() + "已经放了数据，队列目前有" + queue.size() + "个数据");
                        System.out.println("执行次数:" + count.getAndIncrement());
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }



//                }
            }).start();
        }

        //取数据
        new Thread(() -> {
            while (queue.size()> 0) {
                try {
                    System.out.println(Thread.currentThread().getName() + "准备取数据");
                    queue.take();
                    System.out.println(Thread.currentThread().getName() + "已经取走数据，"
                            + "队列目前有" + queue.size() + "个数据");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
